package com.example.interceptor;

import com.example.util.JwtUtil;
import com.example.util.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求路径
        String path = request.getRequestURI();

        //登录注册接口不进行权限验证
        if (path.startsWith("/user/login") || path.startsWith("/user/register")) {
            log.info("登录注册接口不进行权限验证");
            return true;
        }

        //获取请求头中的token
        String token = request.getHeader("Authorization");
        log.info("当前token：{}",token);

        //token为空，返回401
        if (token == null) {
            log.info("用户未登录");
            response.setStatus(401);
            return false;
        }
        //开始校验权限
        try {
            log.info("验证令牌，如果验证失败，则用户没有登录，返回错误信息（响应码401）");
            // 解析token
            Claims claims = JwtUtil.parseJwt(token);
            log.info("解析token成功,clams:{}",claims);
            // 获取当前登录用户id
            Long currentId = claims.get("userId", Long.class);
            log.info("当前登录用户id为：{}",currentId);
            UserContext.setCurrentUserId(currentId);//存入ThreadLocal
            log.info("当前登录用户id为：{},将其存入TreadLocal",currentId);
        } catch (Exception e) {
            log.info("用户没有登录，返回错误信息（响应码401）");
            response.setStatus(401);
            return false;
        }

        //6.如果解析成功，放行
        log.info("用户已登录，放行");
        return true;
    }


}
